package com.wiloon.cherry;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.provider.ContactsContract;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.wiloon.cherry.entity.User;

import java.sql.SQLException;

/**
 * Created by wiloon on 7/25/14.
 */

public class DataHelper extends OrmLiteSqliteOpenHelper {
    public DataHelper(Context context, String databaseName, SQLiteDatabase.CursorFactory factory, int databaseVersion) {
        super(context, databaseName, factory, databaseVersion);
    }

    private Dao<User, Integer> userDao = null;

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        try {
            Log.e(DataHelper.class.getName(), "create database start.");
            TableUtils.createTable(connectionSource, User.class);
            Log.e(DataHelper.class.getName(), "create database done.");
        } catch (SQLException e) {
            Log.e(DataHelper.class.getName(), "create database failed.", e);
        }
    }


    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i2) {
        try {
            TableUtils.dropTable(connectionSource, User.class, true);
            onCreate(sqLiteDatabase, connectionSource);
        } catch (SQLException e) {

        }
    }

    @Override
    public void close() {
        super.close();
    }

    public Dao<User, Integer> getUserDao() throws SQLException {
        if (userDao == null) {
            userDao = getDao(User.class);
        }
        return userDao;
    }
}

